package com.cxf.lock;

import lombok.extern.log4j.Log4j;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 此版本zookeeper分布式锁有两个问题
 * 1）死锁。因为创建的是持久性znode节点，如果客户端挂掉，锁没释放，该节点永远存在
 * 2）惊群。假设有100个客户端去抢锁。第一个线程释放了，将通知其余99个线程。如此反复。第100个线程将收到99次通知！浪费资源
 * 改进版本看ZookeeperLockV2
 * @author xuanfei_Chen
 * @date 2020/4/5 5:33 下午
 */
@Log4j
public class ZookeeperLockV1 implements Lock {

    private static final String ZK_IP_PORT = "127.0.0.1:2181";
    private static final String LOCK_NODE = "/LOCK";

    private ZkClient client = new ZkClient(ZK_IP_PORT);
    private CountDownLatch cdl = null;

    /**
     * 非阻塞性加锁
     * @Author:xuanfei_Chen
     * @Date:5:43 下午 2020/4/5
     */
    @Override
    public boolean tryLock() {
        try {
            client.createPersistent(LOCK_NODE);
            return true;
        }catch (ZkNodeExistsException e){
            return false;
        }
    }

    /**
     * 阻塞性加锁
     * @Author:xuanfei_Chen
     * @Date:5:43 下午 2020/4/5
     */
    @Override
    public void lock() {
        if(tryLock()){
            return;
        }
        waitForLock();
        lock();
    }

    private void waitForLock() {
        IZkDataListener zkDataListener = new IZkDataListener() {

            @Override
            public void handleDataChange(String s, Object o) throws Exception {

            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                log.warn("------------ get data delete event -------------");
                if(cdl != null){
                    cdl.countDown();
                }
            }
        };
        //给节点加监听
        client.subscribeDataChanges(LOCK_NODE, zkDataListener);
        if(client.exists(LOCK_NODE)){
            cdl = new CountDownLatch(1);
            try {
                cdl.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        client.unsubscribeDataChanges(LOCK_NODE, zkDataListener);
    }

    /**
     * 解锁
     * @Author:xuanfei_Chen
     * @Date:5:43 下午 2020/4/5
     */
    @Override
    public void unlock() {
        client.delete(LOCK_NODE);
    }

    @Override
    public Condition newCondition() {
        return null;
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }
}
